package router

import (
	"context"
	"log"
	"net/http"
	"time"

	"go_gateway/golang_common/lib"

	"github.com/gin-gonic/gin"
)

var (
	HttpSrvHandler *http.Server
)

func HttpServerRun() {
	gin.SetMode(lib.GetStringConf("base.base.debug_mode"))
	r := InitRouter()
	HttpSrvHandler = &http.Server{
		Addr:           lib.GetStringConf("base.http.addr"), // 监听地址
		Handler:        r,                                   // 路由处理器
		ReadTimeout:    time.Duration(lib.GetIntConf("base.http.read_timeout")) * time.Second,
		WriteTimeout:   time.Duration(lib.GetIntConf("base.http.write_timeout")) * time.Second,
		MaxHeaderBytes: 1 << uint(lib.GetIntConf("base.http.max_header_bytes")),
	}
	// 使用 goroutine 启动服务器（非阻塞）
	go func() {
		log.Printf(" [INFO] HttpServerRun:%s\n", lib.GetStringConf("base.http.addr"))
		if err := HttpSrvHandler.ListenAndServe(); err != nil {
			log.Fatalf(" [ERROR] HttpServerRun:%s err:%v\n", lib.GetStringConf("base.http.addr"), err)
		}
	}()
}

func HttpServerStop() {
	// 设置合理的超时时间，超时后强制关闭剩余连接
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	if err := HttpSrvHandler.Shutdown(ctx); err != nil {
		log.Fatalf(" [ERROR] HttpServerStop err:%v\n", err)
	}
	log.Printf(" [INFO] HttpServerStop stopped\n")
}

/*
1.优雅关闭
 - 允许处理中的请求完成
 - 拒绝新的连接
 - 避免数据丢失或损坏

2. 资源泄露风险
如果不手动关闭：
 - 文件描述符泄露
 - 内存泄露
 - 端口占用（无法立即重启）
*/
